package com.lungle.warmdiary.app.view.invite.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.AppConstant;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseFragment;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.response.InvestCode;
import com.lungle.warmdiary.app.ui.empty.EmptyLayout;
import com.lungle.warmdiary.app.utils.ShareHelper;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author sbbic
 *         created at 2016/9/7 0:04
 */
public class RecommendFragment extends BaseFragment {
    private static final String RECOMMEND_SCREEN = "recommend screen";


    private WebView mWebView;
    private String mCurrentUrl;
    private String mShareChannel;
    private InvestCode mInvestCode;
    private EmptyLayout mErrorLayout;


    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_recommend, container,
                false);

        initViews(view);
        initData();
        return view;
    }


    public void getMyInvestCode() {
        ApiFactory.getUserApi().getInvitation().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result<InvestCode>>(getActivity()) {
                    @Override
                    public void onNext(Result<InvestCode> result) {
                        mInvestCode = result.getData();
                        String shareUrl = new StringBuilder(AppConstant.URL_INVEST).append("?aidtype=").append(mInvestCode.getCode())
                                .append("&invited=").append(mInvestCode.getUsers()).append("&award=").append(mInvestCode.getAward()).append("&code=").append(mShareChannel).toString();
//                        addShareChannel(mShareChannel);
                        mWebView.loadUrl(shareUrl);

                    }

                    @Override
                    public void onCompleted() {
                        if (mErrorLayout != null) {
                            mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if (mErrorLayout != null) {
                            mErrorLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
                        }
                    }
                });
    }

    @Override
    public void initData() {
        mShareChannel = ShareHelper.obtainInstallList();
        getMyInvestCode();
    }


    private void initViews(View view) {
        mWebView = (WebView) view.findViewById(R.id.webview);
        mErrorLayout = (EmptyLayout) view.findViewById(R.id.error_layout);
        mErrorLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mErrorLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                getMyInvestCode();
            }
        });
        mErrorLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
        initWebview();

    }


    @Override
    public void onResume() {
        super.onResume();
        mWebView.onResume();
        MobclickAgent.onPageStart(RECOMMEND_SCREEN);
        MobclickAgent.onResume(getActivity());

    }

    @Override
    public void onPause() {
        super.onPause();
        mWebView.onPause();
        MobclickAgent.onPageEnd(RECOMMEND_SCREEN);
        MobclickAgent.onPause(getActivity());

    }


    private void share(Activity activity, String title, String text, String link, SHARE_MEDIA platform) {
        ShareAction shareAction = new ShareAction(activity);
        if (!TextUtils.isEmpty(title)) {
            shareAction.withTitle(title);
        }


        if (!TextUtils.isEmpty(text)) {
            shareAction.withText(text);
        }
        UMImage umImage = new UMImage(getActivity(), R.drawable.ic_launcher);
        shareAction.withMedia(umImage);


        if (!TextUtils.isEmpty(link)) {
            shareAction.withTargetUrl(link);
        }
        shareAction.setPlatform(platform).setCallback(mUMShareListener).share();

    }

    private UMShareListener mUMShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA share_media) {
            AppContext.showToast("分享成功");
        }

        @Override
        public void onError(SHARE_MEDIA share_media, Throwable throwable) {
            AppContext.showToast(throwable.getMessage());
            throwable.printStackTrace();
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {
            AppContext.showToast("分享取消");
        }
    };


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(getActivity()).onActivityResult(requestCode, resultCode, data);
    }


    @SuppressLint("SetJavaScriptEnabled")
    @SuppressWarnings("deprecation")
    private void initWebview() {
        // cookie = CookieManager.getInstance();
        WebSettings webSettings = mWebView.getSettings();

        //自适应网页
        webSettings.setUseWideViewPort(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);


        webSettings.setJavaScriptEnabled(true); // 启用支持javascript
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);// 优先使用缓存
        webSettings.setAppCacheEnabled(true);
        webSettings.setAllowFileAccess(true);// 可以访问文件
        webSettings.setBuiltInZoomControls(true);// 支持缩放
        if (Build.VERSION.SDK_INT >= 11) {
            webSettings.setPluginState(WebSettings.PluginState.ON);
            webSettings.setDisplayZoomControls(false);// 支持缩放
        }
        mWebView.addJavascriptInterface(this, "stads");
        mWebView.setWebViewClient(new MyWebViewClient());

        mWebView.setWebChromeClient(new MyWebChromeClient());
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

    }


    private class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            super.onReceivedIcon(view, icon);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) { // 进度
            super.onProgressChanged(view, newProgress);
            if (newProgress > 90) {
                mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);

            }
        }
    }



    protected void onUrlFinished(WebView view, String url) {
        mCurrentUrl = url;
    }


    private class MyWebViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);

        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            boolean flag = super.shouldOverrideUrlLoading(view, url);
            mCurrentUrl = url;
            return flag;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            onUrlFinished(view, url);
        }
    }

    @JavascriptInterface
    public void shareTo(int shareType) {

        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String title = "推荐一款为品牌代言的应用";
                String text = "海量用户真实测评，您只为高质量高信用品牌代言立即下载“首席分享官”，开启您的社交货币变现之旅下载注册时，输入邀请码%s，可立得一元奖励";
                String content = String.format(text, mInvestCode.getCode());
                String shareUrl = new StringBuilder(AppConstant.URL_SHARE_URL).append("?aldtype=").append(mInvestCode.getCode())
                        .toString();

                switch (shareType) {
                    case 0:
                        share(getActivity(), title, content, shareUrl, SHARE_MEDIA.WEIXIN);
                        break;
                    case 1:
                        share(getActivity(), title, content, shareUrl, SHARE_MEDIA.WEIXIN_CIRCLE);
                        break;
                    case 2:
                        share(getActivity(), "", content, shareUrl, SHARE_MEDIA.SINA);
                        break;
                    case 3:
                        share(getActivity(), title, content, shareUrl, SHARE_MEDIA.QZONE);
                        break;
                    case 4:
                        share(getActivity(), title, content, shareUrl, SHARE_MEDIA.QQ);
                        break;
                }
            }
        });


    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mWebView != null)
            mWebView.destroy();
    }

    private void addShareChannel(String value) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mWebView.evaluateJavascript("javascript:window.installMask=\'" + value + "\'", null);
        } else {
            mWebView.loadUrl("javascript:window.installMask=\'" + value + "\'");
        }
    }


}